#include <iostream>
#include "VTKFileWriter.hh"
//#include "Debug.hh"
#include <stdlib.h>

VTKFileWriter::VTKFileWriter(uint xsize, uint ysize, const std::string& problem )
{

    std::string filename = problem;
    filename += ".vtk";
    //std::cout << filename <<std::endl;
    mStream = fopen(filename.c_str(), "w");

    if ( mStream == NULL )
    {
        std::cerr<<"Error opening outputfile";
    }

    fprintf( mStream, "# vtk DataFile Version 3.12.0\n");
    fprintf( mStream, "Nusif %s\n",problem.c_str());
    fprintf( mStream, "ASCII\n");
    fprintf( mStream, "DATASET STRUCTURED_POINTS\n");

    mDataCount = xsize*ysize;
    fprintf( mStream, "DIMENSIONS %d %d 1\n",xsize,ysize);
    fprintf( mStream, "ORIGIN 0 0 0 \n" );
    fprintf( mStream, "SPACING 1 1 1\n");
    fprintf( mStream, "POINT_DATA %d\n\n", mDataCount);
}



VTKFileWriter::~VTKFileWriter( )
{
    fprintf( mStream, "\n" );
    fclose(mStream);
}


void VTKFileWriter::WriteVector(const V_Field &vec,const std::string &name)
{

    fprintf( mStream, "VECTORS %s double\n", name.c_str());
    uint xsize = vec.getxSize();
    uint ysize = vec.getySize();


    for(uint j=0; j<ysize; ++j)
    {
        for(uint i=0; i< xsize; ++i)
        {
            fprintf( mStream, "%f %f 0\n", vec(i,j,0), vec(i,j,1));
        }
    }

}



void VTKFileWriter::WriteScalar(const D_Field &scalar, const std::string &name)
{
    fprintf( mStream, "SCALARS %s double 1\n",name.c_str() );
    fprintf( mStream, "LOOKUP_TABLE default\n");

    uint xsize = scalar.getxSize();
    uint ysize = scalar.getySize();


    for(uint j=0; j<ysize; ++j)
    {
        for(uint i=0; i< xsize; i++)
        {
            fprintf( mStream, "%f\n", scalar(i,j));
        }
    }
}

void VTKFileWriter::WriteFlag(const Flags &flag, const std::string &name)
{
    fprintf( mStream, "SCALARS %s unsigned_int 1\n",name.c_str() );
    fprintf( mStream, "LOOKUP_TABLE default\n");

    uint xsize = flag.getxSize();
    uint ysize = flag.getySize();

    for(uint j=0; j<ysize; ++j)
    {
        for(uint i=0; i< xsize; ++i)
        {
            fprintf( mStream, "%d\n", flag(i,j));
        }
    }
}



